package com.wmz.model;

import com.wmz.constant.BusinessEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author wmz
 * @date 2024/6/30 22:23
 * @description 统一返回结果响应类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("统一返回结果响应类")
public class Result<T> implements Serializable {
    @ApiModelProperty("状态码")
    private Integer code = 200;
    @ApiModelProperty("响应信息")
    private String msg = "OK";
    @ApiModelProperty("响应数据")
    private T data;

    /**
     * 操作成功
     * @param data
     * @return
     * @param <T>
     */
    public static  <T> Result<T> success(T data) {
        Result<T> result = new Result();
        result.setData(data);
        return result;
    }

    /**
     * 操作失败
     * @param code
     * @param msg
     * @return
     * @param <T>
     */
    public static  <T> Result<T> fail(Integer code, String msg) {
        Result<T> result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(null);
        return result;
    }

    /**
     * 操作失败，从枚举类中获取错误信息
     * @param businessEnum
     * @return
     * @param <T>
     */
    public static  <T> Result<T> fail(BusinessEnum businessEnum) {
        Result<T> result = new Result();
        result.setCode(businessEnum.getCode());
        result.setMsg(businessEnum.getDesc());
        result.setData(null);
        return result;
    }

    public static <T> Result handle(boolean flag) {
        if(flag) {
            return Result.success(null);
        }
        return Result.fail(BusinessEnum.OPERATION_FAIL);
    }
}
